using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [Header("速度")]
    public float startSpeed;
    public float currSpeed;
    [Header("伤害")]
    public int damage;//通过一系列计算得到
    [Header("原数值")]
    public int oriDamage=1;
    public int oriArmor = 1;
    public int oriHp;
    [Header("死亡时的数据")]
    public int dieDamage;
    public int dieArmor;
    public int dieHp;
    public int dieOriHp;
    public int dieOriDamage;
    public int dieOriArmor;
    [Header("当前原数值")]
    public int currOriDamage;
    public int currOriArmor;
    [Header("路径")]
    public List<AStarNode> path = new List<AStarNode>();
    public AStar aStar;
    [Header("地上符文")]
    public PlayerGroundTune tuneSc;
    [Header("玩家血量")]
    public int currHp = 100;
    [Header("玩家护甲")]
    public int armor = 10;
    [Header("自身材质")]
    public Material oriMat;
    [Header("自身的spriteRenderer")]
    public SpriteRenderer myRender;
    [Header("羊的步数")]
    public int sheepStep = 0;
    [Header("狗的步数")]
    public int dogStep = 0;
    [Header("拥有的最终剑")]
    public GameObject finalSword;
    [Header("皮肤列表")]//0：原始，1：幽灵
    public List<GameObject> skinList = new List<GameObject>();

    //组件
    public Animator ani;

    //动画方向控制
    public int aniDir = 0;//0:前Idle,1:后Idle,2:左Idel,3:右Idle,4:前,5:后,6:左,7:右

    private void Awake()
    {
        //获取玩家动画
        GetAniMaterial();
    }
    private void Start()
    {
        //添加AStar
        AddAStar();
        //添加地上符文
        tuneSc = GetComponent<PlayerGroundTune>();
    }
    private void Update()
    {
        //搜寻路径
        GetPath();
        //开始移动
        StartRun();
        //设置方向
        PlayAni();
    }
    //将自己放到A星管理
    public void AddAStar()
    {
        aStar = GetComponent<AStar>();
        AStarManager.Instance.AddAStar(aStar);
    }
    //获取路径
    public void GetPath()
    {
        if (GameManager.Instance.canOprate == false) return;
        if(Input.GetMouseButtonDown(0)&&GameManager.Instance.canOprate)
        {
            ////关闭打开的敌人碰撞体
            //if(!SceneItemManager.instance.clickEnemyRight)
            //{
            //    SceneItemManager.instance.ClearClickEnemy();
            //}
            //获取屏幕坐标
            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            path = aStar.SeekPath(Mathf.RoundToInt(transform.position.x),
            Mathf.RoundToInt(transform.position.y), Mathf.RoundToInt(mousePos.x)
            , Mathf.RoundToInt(mousePos.y));
            //清空符文
            tuneSc.ClearAllTune();
            //创建符文
            tuneSc.CreateTune(path);
            //关闭点击敌人
            if(aStar.isEnemy==false)
            {
                SceneItemManager.instance.ClearClickEnemy();
                //SceneItemManager.instance.clickEnemyRight = false;
            }
            //如果path为空，设置状态
            if (path==null||path.Count <= 0)
            {
                SetIdleAni();
            }
            else
            {
                //不为空才算点击
                AudManager.instance.PlayUIAud(AudManager.instance.uiDic["点击"], 1f);
            }
        }
    }
    //开始行走
    public void StartRun()
    {
        if (GameManager.Instance.canOprate == false) return;
        if (path == null) return;
        if (path.Count <= 0) return;

        //获取列表第一个值
        Vector2 pos = path[0].pos;
        Vector2 dir = (pos - (Vector2)transform.position).normalized;
        Move(dir);
        //设置动画
        SetRunAni(dir);
        if(Vector2.Distance(transform.position,pos)<=0.1)
        {
            transform.position = pos;
            //移除此点
            path.RemoveAt(0);
            //销毁符文
            Destroy(tuneSc.groundTune[0]);
            tuneSc.groundTune.RemoveAt(0);
            //增加
            AddSheepStep();
            AddDogStep();
            //如果此时需要停下
            if(path.Count<=0)
            {
                //设置动画
                SetIdleAni();
            }
        }
    }
    //玩家移动
    public void Move(Vector2 dir)
    {
        transform.Translate(dir * currSpeed * Time.deltaTime);
    }
    //玩家停止
    public void StopPlayer()
    {
        if (path==null) return;
        //清空列表
        path.Clear();
        //让玩家停在此坐标
        transform.position = new Vector3(Mathf.RoundToInt(transform.position.x)
            ,Mathf.RoundToInt(transform.position.y), 0);
        //清空所有符文
        tuneSc.ClearAllTune();
        //设置方向动画
        SetIdleAni();
    }
    //玩家受伤
    public void BeHurt(int amount)
    {
        if (currHp<=0) return;

        int hurtNum = CalculateFinalHurt(amount);

        //是否拥有魔戒
        if(ArtifactManager.instance.SeekArtifact("魔戒"))
        {
            if(GameManager.Instance.canHaveHurtEnd)
            {
                //免疫此次伤害
                GameManager.Instance.CreateOtherText("免疫",transform.position);
                GameManager.Instance.canHaveHurtEnd=false;
                AudManager.instance.PlayEnemyAud(AudManager.instance.enemyDic["闪避"], 1f);
                //增加一半血量
                AddHp(Mathf.RoundToInt(amount/2));
                return;
            }
        }
        //闪避值
        int currAvoidNum = 0;
        //是否佩戴蛇
        if(TurnManager.instance.SeekTurn("蛇"))
        {
            currAvoidNum+=30;
        }
        //是否佩戴猪
        if (TurnManager.instance.SeekTurn("鼠"))
        {
            currAvoidNum+=10;
        }
        if (currAvoidNum>0)
        {
            if (Random.Range(0, 100)<=currAvoidNum)
            {
                //免疫此次伤害
                GameManager.Instance.CreateOtherText("闪避", transform.position);
                GameManager.Instance.canHaveHurtEnd=false;
                AudManager.instance.PlayEnemyAud(AudManager.instance.enemyDic["闪避"], 1f);
                return;
            }
        }
        currHp -= hurtNum;
        oriHp-=hurtNum;
        dieHp-=hurtNum;
        dieOriHp-=amount;
        //更新UI
        GameManager.Instance.UpdateMathData();
        //受伤特效
        StartCoroutine(BeHurtEffect());

        //伤害数字
        GameManager.Instance.CreateHurtDamage(hurtNum,transform.position);
        if(currHp<=0)
        {
            Die();
        }
        AudManager.instance.PlayEnemyAud(AudManager.instance.enemyDic["受伤"], 1f);
    }
    //增加玩家血量
    public void AddHp(int amount)
    {
        //增加生命
        GameManager.Instance.CreateAddHpNum(amount, transform.position);
        //生成特效
        currHp+=amount;
        oriHp+=amount;
        dieHp+=amount;
        dieOriHp+=amount;
        //更新UI
        GameManager.Instance.UpdateMathData();
    }
    //减少玩家血量
    public void ReHp(int amount)
    {
        if (currHp<=0) return;
        //生成特效
        BeHurt(amount);
        //更新UI
        GameManager.Instance.UpdateMathData();
    }
    //获取玩家攻击力
    public int GetPlayerDamage()
    {
        int finalDamage = damage;

        return finalDamage;
    }
    //计算最终攻击
    public int CalculateFinalDamage(int _damage,Enemy enemy)
    {
        int finalDamage = damage;
        //如果有龙符咒
        if (TurnManager.instance.SeekTurn("龙"))
        {
            finalDamage=damage+armor;
        }
        //获取敌人的防御
        int currAomor = enemy.data.armor;
        //如果敌人防御小于自身攻击力
        if(_damage>=currAomor)
        {
            //增伤比例限制为50%以内
            float addDamage = (float)((_damage-currAomor) / (currAomor*1.0f));
            addDamage = addDamage > 0.5f ? 0.5f : addDamage;
            finalDamage= _damage + Mathf.RoundToInt((_damage * addDamage));
        }
        else
        {
            //减伤比例限制为50%
            float deDamage = (float)((currAomor-_damage) / (currAomor*1.0f));
            deDamage = deDamage > 0.5f ? 0.5f : deDamage;
            finalDamage= _damage - Mathf.RoundToInt(_damage * deDamage);
        }
        //如果有猴符咒
        if (TurnManager.instance.SeekTurn("猴"))
        {
            if (Random.Range(0, 100)<=40)
            {
                int index = Mathf.RoundToInt(finalDamage*0.4f);
                finalDamage+=index<=0 ? 0 : index;
            }
        }

        return finalDamage;
    }
    //计算玩家此时的最终攻击，注意加上羊，狗符咒，不要有运气符咒
    public int CalculateCurrFinalDamage(int _damage,Enemy enemy)
    {
        int finalDamage = damage;
        //获取其他增益
        Vector2 currData = GetOtherMondify(enemy);
        //如果有虎符咒
        if(TurnManager.instance.SeekTurn("虎"))
        {
            finalDamage = Mathf.RoundToInt((currData.x+currData.y)*1.2f);
        }
        //如果有龙符咒
        if (TurnManager.instance.SeekTurn("龙"))
        {
            finalDamage=Mathf.RoundToInt(currData.x)+Mathf.RoundToInt(currData.y);
        }
        //获取敌人的防御
        int currAomor = enemy.data.armor;
        //如果敌人防御小于自身攻击力
        if (_damage>=currAomor)
        {
            //增伤比例限制为50%以内
            float addDamage = (float)((_damage-currAomor) / (currAomor*1.0f));
            addDamage = addDamage > 0.5f ? 0.5f : addDamage;
            finalDamage= _damage + Mathf.RoundToInt((_damage * addDamage));
        }
        else
        {
            //减伤比例限制为50%
            float deDamage = (float)((currAomor-_damage) / (currAomor*1.0f));
            deDamage = deDamage > 0.5f ? 0.5f : deDamage;
            finalDamage= _damage - Mathf.RoundToInt(_damage * deDamage);
        }

        return finalDamage*enemy.data.damageNum;
    }
    //计算玩家最后的防御，注意加上增益效果
    public int CalculateCurrFinalArmor(int _armor,Enemy enemy)
    {
        int finalArmor = armor;

        //盾之心
        //如果拥有盾之心
        if (ArtifactManager.instance.SeekArtifact("盾之心"))
        {
            int addnum = Mathf.RoundToInt((enemy.data.armor*0.5f));
            finalArmor+= addnum<1 ? 1 : addnum;
        }
        //血月
        //如果是血月，且拥有月星
        if (GameManager.Instance.isBloodMoon&&ArtifactManager.instance.SeekArtifact("月星"))
        {
            int addnum = Mathf.RoundToInt((finalArmor*0.5f));
            finalArmor+=addnum<1 ? 1 : addnum;
        }
        //狗符咒
        //如果有狗符咒
        if (TurnManager.instance.SeekTurn("狗"))
        {
            int index = Mathf.RoundToInt(finalArmor*(dogStep/100.0f));
            finalArmor+=index<=0 ? 0 : index;
        }

        return finalArmor;
    }
    //计算最终受伤
    public int CalculateFinalHurt(int _damage)
    {
        int finalArmor = armor;
        //查看防御是不是高于攻击
        //还是一样的增伤和减伤50%
        if(_damage>=armor)
        {
            float addDamage = (float)((_damage-armor) / (armor*1.0f));
            addDamage = addDamage > 0.5f ? 0.5f : addDamage;
            finalArmor = _damage + Mathf.RoundToInt(addDamage * _damage);
        }
        else
        {
            float deDamage = (float)((armor-_damage) / (armor*1.0));
            deDamage = deDamage > 0.9f ? 0.9f : deDamage;
            finalArmor = _damage - Mathf.RoundToInt(deDamage * _damage);
            finalArmor=finalArmor<=0 ? 1 : finalArmor;
        }

        return finalArmor;
    }
    //玩家死亡
    public void Die()
    {
        //打开死亡界面
        PanelManager.Open<DiePanel>();
        //关闭守塔人战斗
        CloseTowerBoss();
    }
    //关闭守塔战斗
    public void CloseTowerBoss()
    {
        if(GameManager.Instance.towerMan!=null)
        {
            //关闭Boss战斗
            PanelManager.Close("FinalSwordPanel");
            TowerMan towerMan = GameManager.Instance.towerMan.GetComponent<TowerMan>();
            towerMan.canBattle=false;
            towerMan.DesAllAttack();
            StopPlayer();
        }
    }
    //播放动画
    public void PlayAni()
    {
        ani.SetInteger("Dir", aniDir);
    }
    //设置Run
    public void SetRunAni(Vector2 dir)
    {
        if(Mathf.Abs(dir.x)> Mathf.Abs(dir.y))
        {
            if (dir.x > 0f)
            {
                aniDir = 7;
            }
            else if (dir.x < 0f)
            {
                aniDir = 6;
            }
        }
        else
        {
            if (dir.y > 0)
            {
                aniDir = 5;
            }
            if (dir.y < 0)
            {
                aniDir = 4;
            }
        }
    }
    //设置Idle
    public void SetIdleAni()
    {
        switch (aniDir)
        {
            case 4: aniDir = 0; break;
            case 5: aniDir = 1; break;
            case 6: aniDir = 2; break;
            case 7: aniDir = 3; break;
        }
    }
    //被伤害
    public IEnumerator BeHurtEffect()
    {
        myRender.material = PoolManager.Instance.hurtMat;

        yield return new WaitForSeconds(0.15f);

        myRender.material = oriMat;
    }
    //增加羊步数
    public void AddSheepStep()
    {
        if(TurnManager.instance.SeekTurn("羊"))
        {
            sheepStep+=1;
            if (sheepStep>30) sheepStep=30;
            MsgStepUI msg = new MsgStepUI();
            msg.str="羊";
            EventManager.AddMsg(msg);
        }
    }
    //增加狗步数
    public void AddDogStep()
    {
        if (TurnManager.instance.SeekTurn("狗"))
        {
            dogStep+=1;
            if (dogStep>30) dogStep=30;
            MsgStepUI msg = new MsgStepUI();
            msg.str="狗";
            EventManager.AddMsg(msg);
        }
    }
    //打开最终剑
    public void OpenFinalSword()
    {
        if(GameManager.Instance.haveSword)
        {
            finalSword.SetActive(true);
        }
        else
        {
            finalSword.SetActive(false);
        }
    }
    //获取其他增益效果
    public Vector2 GetOtherMondify(Enemy enemy)
    {
        int currArmor = armor;
        int currDamage = damage;
        //如果拥有盾之心
        if (ArtifactManager.instance.SeekArtifact("盾之心"))
        {
            int addnum = Mathf.RoundToInt((enemy.data.armor*0.5f));
            currArmor+= addnum<1 ? 1 : addnum;
        }
        //如果是血月，且拥有月星
        if (GameManager.Instance.isBloodMoon&&ArtifactManager.instance.SeekArtifact("月星"))
        {
            int addnum = Mathf.RoundToInt((currArmor*0.5f));
            currArmor+=addnum<1 ? 1 : addnum;
            addnum = Mathf.RoundToInt((currDamage*0.5f));
            currDamage+=addnum<1 ? 1 : addnum;
        }
        //如果有羊符咒
        if (TurnManager.instance.SeekTurn("羊"))
        {
            int index = Mathf.RoundToInt(currDamage*(sheepStep/100.0f));
            currDamage+=index<=0 ? 0 : index;
        }
        //如果有狗符咒
        if (TurnManager.instance.SeekTurn("狗"))
        {
            int index = Mathf.RoundToInt(currArmor*(dogStep/100.0f));
            currArmor+=index<=0 ? 0 : index;
        }

        return new Vector2(currDamage, currArmor);
    }
    //设置死亡数据
    public void SetDieData()
    {
        dieHp=currHp;
        dieDamage=damage;
        dieArmor=armor;
        dieOriHp=oriHp;
        dieOriDamage=oriDamage;
        dieOriArmor=oriArmor;
    }
    //获取动画和材质
    public void GetAniMaterial()
    {
        //关闭所有皮肤
        foreach(var i in skinList)
        {
            i.SetActive(false);
        }

        if (!GameManager.Instance.playerDieData.isDie)
        {
            ChoosePlayerSprite();
        }
        else
        {
            //寻找死灵状态
            GetMyMaterialAndAni(skinList[1]);
        }
    }
    //选择角色
    public void ChoosePlayerSprite()
    {
        GetMyMaterialAndAni(skinList[0]);
    }
    //获取
    public void GetMyMaterialAndAni(GameObject obj)
    {
        //获取组件
        ani = obj.GetComponent<Animator>();
        //获取材质
        oriMat = obj.GetComponent<SpriteRenderer>().material;
        obj.SetActive(true);
        myRender=obj.GetComponent<SpriteRenderer>();
    }
}